<?php
// Library files
include 'includes/cPlayer.php';
include 'includes/cMember.php';
include 'includes/cDatabase.php';
include 'includes/variables.php';
include 'includes/cPage.php';
include 'includes/cGame.php';
include 'includes/cDates.php';
include 'includes/cTransfer.php';

define("TD_DEFAULT", "<td rowspan='n' colspan='n' width='n' align='center|right' valign='top|bottom' bgcolor='n'>");
define("TD_JPEG", "<td width='50' align='center'>");
define("TD_POSITION", "<td width='50' align='center'>");
define("TD_CODE", "<td width='30' align='center'>");
define("TD_NAME", "<td width='100' align='left'>");
define("TD_TEAM", "<td width='10' align='center'>");
define("TD_VALUE", "<td width='10' align='left'>");
define("TD_SCORE", "<td width='50' align='center'>");
define("TD_HEADING", "<td rowspan='1' colspan='8' align='center' valign='top'>");
define("TD_CAT", "<td width='200' align='left'>");

$cPage = new page("Teams");
echo $cPage->getTitle();
echo $cPage->pageStringStart();
echo $cPage->contentStringStart();

$cDatabase = new database();
$connect = $cDatabase->connectToDatabase();
$activeDatabase = $cDatabase->getActiveDatabase($connect);
$db = $cDatabase->selectDatabase($connect, $activeDatabase);

//------------------------------------------------------------------------------------
if(@$_GET['form'] == "one")
{
	$captainForWeek = array();
	$error = 0;
	$j = 0;
	$k = 0;
	
	$memberName = $_POST['memberName'];
	$cPlayer = array();
	
	$prevPlayerCodeList = array();
	$currPlayerCodeList = array();
	
	$maxWeeks = $cDatabase->GetMaxWeeks($connect);
	$captainsEnabled = $cDatabase->GetCaptainsEnabled($connect);
	
	$selectArray[0] = '*';
	$result = $cDatabase->selectFromDatabase($connect, 'memberlist', $selectArray, 'memberName', $memberName, NULL, NULL);
	
	$finfo = mysqli_fetch_fields($result);
	$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
	
	// Get all the data for this member and put it in the class
	$cMember = new member;

	$error |= $cMember->setMemberName($row['memberName']);
	$error |= $cMember->setTeamName($row['teamName']);
	$error |= $cMember->setMoneyPaid($row['moneyPaid']);
	$error |= $cMember->setActive($row['active']);
	$error |= $cMember->setMiniPop($row['miniPop']);
	$cMember->loadCaptainArray($row);
	
	for ($i = 1; $i <= MAXPLAYERS; $i++)
	{
		$playerCodeVariable = getPlayerCodeVariable($i);
		$playerWeekInVariable = getPlayerWeekInVariable($i);
		$playerWeekOutVariable = getPlayerWeekOutVariable($i);

		if ($row[$playerCodeVariable] != NULL)
		{
			$cPlayer[$i] = new player($row[$playerCodeVariable]);
			$error |= $cPlayer[$i]->setPlayerWeekIn($row[$playerWeekInVariable]);
			$error |= $cPlayer[$i]->setPlayerWeekOut($row[$playerWeekOutVariable]);
			$error |= $cPlayer[$i]->setPlayerName($connect);
			$error |= $cPlayer[$i]->setPlayerTeam($connect);
			$error |= $cPlayer[$i]->setPlayerPosition($connect);
			$error |= $cPlayer[$i]->setPlayerValue($connect);
			$error |= $cPlayer[$i]->setPlayerActive($connect);
			
			if ($captainsEnabled)
			{
				$captainForWeek = loadCaptainForWeekArray($captainForWeek, $maxWeeks, $cPlayer[$i], $cMember);
			}
		
			if ($cPlayer[$i]->getPlayerCode() != NULL)							// Is this a valid player
			{
				$cPlayer[$i]->calculatePlayerScore($connect);
				if ($cPlayer[$i]->getPlayerWeekOut() != NULL)					// This player has been subbed out
				{
					$prevPlayerCodeList[$j] = $cPlayer[$i]->getPlayerCode();	// Put it into the subs array
					$j++;														// Index starts at 0 to help sort function
					if ($captainsEnabled == 0)
					{
						$error |= $cMember->addPlayerScore($cPlayer[$i]->getPlayerScore($maxWeeks), 'PREV');
					}
					else
					{
						$error |= $cMember->addPlayerScore($cPlayer[$i]->getPlayerScoreCaptains($maxWeeks, $captainForWeek), 'PREV');
					}
				}
				else															// This player is in the current XI
				{
					$currPlayerCodeList[$k] = $cPlayer[$i]->getPlayerCode();	// Put it into the curr array
					$k++;
					$error |= $cMember->addPlayerValue($cPlayer[$i]->getPlayerValue());
					if ($captainsEnabled == 0)
					{
						$error |= $cMember->addPlayerScore($cPlayer[$i]->getPlayerScore($maxWeeks), 'CURR');
					}
					else
					{
						$error |= $cMember->addPlayerScore($cPlayer[$i]->getPlayerScoreCaptains($maxWeeks, $captainForWeek), 'CURR');
					}
					$error |= $cMember->addFormation( $cPlayer[$i]->getPlayerPosition() );
				}
			}
		}
	}
	sort($prevPlayerCodeList);
	sort($currPlayerCodeList);
	
	// Get current week
	$cDates = new dates;
	$currentWeek = $cDates->getCurrentWeek();
	if ($currentWeek < 1)
		$currentWeek = 1;
			
	$cTransfer = new transfer();
	$currentCaptain = $cTransfer->getCaptainCodeForWeek($cMember->getTeamName(), $currentWeek);
	displayTeam($cPlayer, $cMember, $playerCodes, $prevPlayerCodeList, $currPlayerCodeList, $maxWeeks, $captainsEnabled, $currentCaptain, $cDatabase, $connect);
	//$cDatabase->closeDatabase($connect);
}
else if(@$_GET['form2'] == "two")
{
	echo "form2";
}
else
{
	$selectArray[0] = '*';
	$result = $cDatabase->selectFromDatabase($connect, 'memberlist', $selectArray, NULL, NULL, NULL, NULL);
	
	$finfo = mysqli_fetch_fields($result);
	$numberRows = mysqli_num_rows($result);
	
	?>
	<div align="center">
	<form action="<?php echo $_SERVER['PHP_SELF'] ?>?form=one" method="POST">
	  	<table border='0'>
			<tr><td>
	    		<select name="memberName">
				<?php
				for ($j = 0; $j < $numberRows; $j++)
				{
					$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
	    		  	echo"<option value = '" .$row['memberName']. "'>" .$row['memberName']. "</option>";
				}
				?>
		        </select></td><td>
	    		<input id="fflbutton" name="selectMemberButton" type="submit" id="selectMember" value="Select Team">
				</td></tr>	
	  	</table>
	</form></div>

	
	<?php
	//$cDatabase->closeDatabase($connect);
}
//------------------------------------------------------------------------------------

function loadCaptainForWeekArray($captainForWeek, $maxWeeks, $cPlayer, $cMember)
{
	for ($week = 1; $week <= $maxWeeks; $week++)
	{
		// See if this playercode is in the list of captains per week
		if ($cPlayer->getPlayerCode() == $cMember->getCaptainForWeek($week))
		{
			$captainForWeek[$week] = 1;
		}
		else
		{
			$captainForWeek[$week] = 0;
		}
	}
	
	return $captainForWeek;
}
			
function displayTeam($cPlayer, $cMember, $playerCodes, $prevPlayerCodeList, $currPlayerCodeList, $maxWeeks, $captainsEnabled, $currentCaptain, $cDatabase, $connect)
{
	$PHP_SELF = $_SERVER['PHP_SELF'];
	$k = 0;

	echo "<table width='1000' border='1'>";
	echo "<tr>";
	// Starting XI table
	echo "<td rowspan='12' colspan='8'><table>";
	for ($i = 0; $i < 11; $i++)
	{
		for ($l = 1; $l <= MAXPLAYERS; $l++)
		{
			if ($cPlayer[$l] != NULL)
			{
				// See if this player is in the current list and check he hasn't been subbed out e.g. get Van Persie, transfer him out then get him back in!
				if (($cPlayer[$l]->getPlayerCode() == $currPlayerCodeList[$i]) && ($cPlayer[$l]->getPlayerWeekOut() == NULL))
				{	// We've found the player in the cPlayer structure
					break;
				}
			}
		}
		echo "<tr>";
		// This player is in the current lineup
		$selectArray[0] = '*';
		$injuryResult = $cDatabase->selectFromDatabase($connect, 'injury', $selectArray, "player", $cPlayer[$l]->getPlayerName(), NULL, NULL);
		$injuryRow = mysqli_fetch_array($injuryResult, MYSQLI_ASSOC);
		if (@mysqli_num_rows($injuryResult) != 0)
		{
			$injured = 1;
		}
		else
		{
			$injured = 0;
		}
		
		if ($injured == 0)
		{
			if ($cPlayer[$l]->getPlayerCode() == $currentCaptain)
			{
				echo TD_JPEG."<img src='JPEGs/captain.jpg' width='50' height='50'></td>";
			}
			else
			{
				$path = $cPlayer[$l]->shirtLookup();
				echo TD_JPEG."<img src='".$path."' width='50' height='50'></td>";
			}
		}
		else
		{
			if ($cPlayer[$l]->getPlayerCode() == $currentCaptain)
			{
				echo TD_JPEG."<img src='JPEGs/injuredCaptain.gif' width='50' height='50'></td>";
			}
			else
			{
				echo TD_JPEG."<img src='JPEGs/injured.gif' width='50' height='50'></td>";
			}
		}
		
		echo TD_POSITION.BLUE.$cPlayer[$l]->getPlayerPosition()."</td>";	// Position
		echo TD_CODE.BLUE.$cPlayer[$l]->getPlayerCode()."</td>";			// Code
		echo TD_NAME.BLUE."<A STYLE='text-decoration:none;color:blue' href='DB_ShowPlayers.php?localPlayerCode=".$cPlayer[$l]->getPlayerCode()."'>".$cPlayer[$l]->getPlayerName()."</a></td>";			// Name
		echo TD_TEAM.BLUE.$cPlayer[$l]->getPlayerTeam()."</td>";			// Team
		echo TD_VALUE.BLUE.$cPlayer[$l]->getPlayerValue()."m</td>";			// Value
		if ($captainsEnabled == 0)
		{
			$playerScore = $cPlayer[$l]->getPlayerScore($maxWeeks);
		}
		else
		{
			$captainForWeek = array();
			$captainForWeek = loadCaptainForWeekArray($captainForWeek, $maxWeeks, $cPlayer[$l], $cMember);
			$playerScore = $cPlayer[$l]->getPlayerScoreCaptains($maxWeeks, $captainForWeek);
		}
		echo TD_SCORE.BLUE.$playerScore."</font></td>";	// Score
		echo "<td>&nbsp;</td>";
		echo "</tr>";
	}
	echo "<tr>";
	echo "<td colspan='3'></td>";
	echo TD_NAME."<strong>Sub Total</strong></td><td></td>".TD_VALUE."<strong>".$cMember->getTeamValue()."m</strong></td>";
	echo TD_SCORE."<strong>".$cMember->getTotalScore('CURR')."</strong></td></tr>";
	echo "</table></td>";
	
	// Substitutes Table
	echo "<td><table rowspan='7' colspan='8'>";
	echo "<tr>".TD_HEADING.RED."<strong>Players substituted out</strong></td></tr>";
	for ($i = 0; $i < sizeof($prevPlayerCodeList); $i++)
	{
		if ($prevPlayerCodeList[$i] != NULL)	// See if we have a sub
		{
			for ($l = 1; $l <= MAXPLAYERS; $l++)
			{	// Find the entry for this player
				if ($cPlayer[$l]->getPlayerCode() == $prevPlayerCodeList[$i])
				{	// We've found the sub in the cPlayer structure
					break;
				}
			}
			echo "<tr>";
			$path = $cPlayer[$l]->shirtLookup();
			echo "<td>".RED."SUB0".($i + 1)."</td>";
			echo TD_JPEG."<img src='".$path."' width='50' height='50'></td>";
			echo TD_POSITION.RED.$cPlayer[$l]->getPlayerPosition()."</td>";		// Position
			echo TD_CODE.RED.$cPlayer[$l]->getPlayerCode()."</td>";				// Code
			echo TD_NAME.RED."<A STYLE='text-decoration:none;color:red' href='DB_ShowPlayers.php?localPlayerCode=".$cPlayer[$l]->getPlayerCode()."'>".$cPlayer[$l]->getPlayerName()."</a></td>";				// Name
			echo TD_TEAM.RED.$cPlayer[$l]->getPlayerTeam()."</td>";				// Team
			echo TD_VALUE.RED.$cPlayer[$l]->getPlayerValue()."m</td>";			// Value
			if ($captainsEnabled == 0)
			{
				$playerScore = $cPlayer[$l]->getPlayerScore($maxWeeks);
			}
			else
			{
				$captainForWeek = array();
				$captainForWeek = loadCaptainForWeekArray($captainForWeek, $maxWeeks, $cPlayer[$l], $cMember);
				$playerScore = $cPlayer[$l]->getPlayerScoreCaptains($maxWeeks, $captainForWeek);
			}
			echo TD_SCORE.RED.$playerScore."</font></td>";	// Score
			echo "</tr>";
		}
	}
	for ($i = sizeof($prevPlayerCodeList); $i < 6; $i++)
	{
		echo "<tr>";
		echo "<td>".RED."SUB0".($i + 1)."</td>";
		echo TD_JPEG."<img src='/JPEGs/Blank.gif' width='50' height='50'></td>";
		echo "</tr>";
	}
	echo "<tr>";
	echo "<td colspan='4'></td>";
	echo TD_NAME."<strong>Sub Total</strong></td><td colspan='2'></td>".TD_SCORE."<strong>".$cMember->getTotalScore('PREV')."</strong></td>";
	
	
	echo "</tr>";
	echo "</table></td>";
	echo "</tr>";
	
	// Other information table
	echo "<tr>";
	echo "<td><table>";
	echo "<tr>".TD_CAT."<strong>Team Name</strong></td><td><strong>".BLUE.$cMember->getTeamName()."</font></strong></td></tr>";
	echo "<tr>".TD_CAT."<strong>Member Name</strong></td><td><strong>".BLUE.$cMember->getMemberName()."</font></strong></td></tr>";
	echo "<tr>".TD_CAT."Current Formation</td><td>".BLUE.$cMember->getCurrentFormation()."</font></td></tr>";

	if ( ( MAXTRANSFERS - sizeof($prevPlayerCodeList) ) < 0 )
		$colour = RED;
	else
		$colour = BLUE;
	echo "<tr>".TD_CAT."Transfers Remaining</td><td>".$colour.(MAXTRANSFERS - sizeof($prevPlayerCodeList))."</font></td></tr>";

	if ($cMember->getMoneyPaid() == 0)
		$colour = RED;
	else
		$colour = BLUE;
	echo "<tr>".TD_CAT."Money Paid</td><td>".$colour."&#163;".$cMember->getMoneyPaid()."</font></td></tr>";

	if ( $cMember->getMoneyOwed( sizeof($prevPlayerCodeList) ) < 0)
		$colour = RED;
	else
		$colour = BLUE;	
		
	echo "<tr><td>Balance</td><td>".$colour."&#163;".$cMember->getMoneyOwed( sizeof($prevPlayerCodeList) )."</font></td></tr>";
	
	$cDates = new dates;
	$currentWeek = $cDates->getCurrentWeek();

	$cGame = new game;
	$cGame->calculatePositionsPerWeek();
	for ($var = 0; $var < $cGame->getNumOfMembers(); $var++)
	{	
		if ($cGame->cMember[$var]->getMemberName() == $cMember->getMemberName())
		{
			$position = $cGame->cMember[$var]->getPosition($currentWeek);
		}
	}
	
	echo "<tr>".TD_CAT."<strong>Position</strong></td><td><strong>".$position."/".$cGame->getNumOfMembers()."</strong></td></tr>";
	echo "<tr>".TD_CAT."<strong>TOTAL SCORE</strong></td><td><strong>".$cMember->getTotalScore('TOTAL')."</strong></td>";
	
	echo "<FORM METHOD=\"POST\">";
	echo "<td valign='bottom'><INPUT TYPE='BUTTON' VALUE='Show Team Stats' ONCLICK=\" window.location.href='DB_ShowTeamsStats.php?memberName=".$cMember->getMemberName()."' \"></td>";
	echo "</form></tr>";
	
	echo "</table></td>";
	echo "</tr>";
	
	echo "</table>";	
}

echo $cPage->getContentStringEnd();
echo $cPage->getMenu();
echo $cPage->getClear();
echo $cPage->pageStringEnd();
echo $cPage->getFooter();
?>
